#!/bin/sh
#
#  partition: -t crypto_LUKS /dev/sdb1 /mnt/sdb1
#  filemnt  : file file mountpoint
#

cryptsetup --help || ERRMSG="You must have a working cryptsetup installed"
modprobe dm-crypt || ERRMSG="Can't continue: dm-crypt kernel module not found.."
modprobe xts  || ERRMSG="Can't continue: xts kernel module not found.."

if [ "$ERRMSG" ] ; then
	pidof Xorg && DISPLAY=:0 /usr/lib/gtkdialog/box_ok "Error" error "You must install cryptsetup first"
	exit 1
fi

[ -f /root/.gtkrc-2.0 ] && export GTK2_RC_FILES=/root/.gtkrc-2.0

#=============================================================
#                      filemnt
#=============================================================

if [ "$1" = "file" ] ; then
	imgFile="$2" MntPt="$3" DEVLOOP=$(losetup -f)
	modprobe dm-crypt
	imgFileBASE=${imgFile##*/}
	imgFileBASE=${imgFileBASE##*\+}
	MYPASS="$(/usr/lib/gtkdialog/box_passwd "$(gettext 'Password required')" "$(gettext 'Password required to open') $imgFileBASE")" || exit 1
    if [ $? -eq 0 ] ; then
		losetup $DEVLOOP "$imgFile"
		echo -n "$MYPASS" | cryptsetup luksOpen $DEVLOOP luksfile$$ -
		mount /dev/mapper/luksfile$$ "$MntPt"
		if [ $? -ne 0 ] ; then
			cryptsetup luksClose luksfile$$
			exit 1
		fi
	fi
	exit
fi

#=============================================================
#                      PARTITION
#=============================================================

wc=$(echo "${@}" | tr -s ' ' | wc -w)
DEVICE=$(echo "$@" | cut -f $(($wc-1)) -d ' ')
MOUNTPOINT=$(echo "$@" | cut -f $wc -d ' ')

if grep -m1 " $MOUNTPOINT " /proc/mounts ; then
	exit 0
fi

DEVNAME=${DEVICE##*/}

if pidof Xorg ; then
	MYPASS="$(DISPLAY=:0 /usr/lib/gtkdialog/box_passwd "Password required" "Password required to open $MOUNTPOINT")"
	if [ $? -eq 0 ] ; then
		echo -n "$MYPASS" | cryptsetup luksOpen $DEVICE lukspartition_${DEVNAME} -
		mount-FULL -n /dev/mapper/lukspartition_${DEVNAME} "$MOUNTPOINT"
		RETVAL=$?
	else
		exit 1
	fi
else
	cryptsetup luksOpen $DEVICE lukspartition_${DEVNAME} -
	mount-FULL -n /dev/mapper/lukspartition_${DEVNAME} "$MOUNTPOINT"
	RETVAL=$?
fi

if [ $RETVAL -ne 0 ] ; then
	cryptsetup luksClose lukspartition_${DEVNAME}
	exit 1
fi

if [ $RETVAL -eq 0 ] ; then
	if [ -f /usr/local/pup_event/frontend_funcs ] ; then
		#ROX: create or refresh desktop icon
		/usr/local/pup_event/frontend_funcs rox_mount_luks "$DEVNAME"
	fi
fi

#v409, instead just make sure the symlink stays there...
if [ ! -L /etc/mtab ];then
 rm -f /etc/mtab
 ln -s /proc/mounts /etc/mtab
fi

exit $RETVAL


### END ###
